package com.changwen.currentactivity.accessibility;

import android.content.Context;
import android.provider.Settings;
import android.util.Log;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ShellUtils;
import com.blankj.utilcode.util.ToastUtils;

/**
 * @author lcw
 * @date 2019/6/28
 * @desc
 */
public class AcbPermissionUtils {

    public static boolean openAccessibilityService(Context context, final Class<?> service) {
        String cmd1 = "settings put secure enabled_accessibility_services " + context.getPackageName() + "/" + service.getName();
        String cmd2 = "settings put secure accessibility_enabled 1";
        String[] cmds = new String[]{cmd1, cmd2};
        ShellUtils.CommandResult commandResult = ShellUtils.execCmd(cmds, true);
        LogUtils.d(commandResult);
        return 0 == commandResult.result;
    }

    public static boolean closeAccessibilityService(Context context, final Class<?> service) {
        String cmd1 = "settings put secure enabled_accessibility_services " + context.getPackageName() + "/" + service.getName();
        String cmd2 = "settings put secure accessibility_enabled 0";
        String[] cmds = new String[]{cmd1, cmd2};
        ShellUtils.CommandResult commandResult = ShellUtils.execCmd(cmds, true);
        LogUtils.d(commandResult);
        return 0 == commandResult.result;
    }

    /**
     * ADB操作无障碍服务
     *
     * @param context 上下文
     * @param service 对应无障碍服务
     * @param command 1:开启，0关闭
     * @return
     */
    public static boolean openAccessibilityService(Context context, final Class<?> service, final int command) {
        try {
            String enabledServices = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            String services = enabledServices + ":" + context.getPackageName() + "/" + service.getName();
            Settings.Secure.putString(context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, services);
            Settings.Secure.putString(context.getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED, String.valueOf(command));
            ToastUtils.showLong("成功开启辅助服务");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            //授权方法：开启usb调试并使用adb工具连接手机，执行 adb shell pm grant 包名 android.permission.WRITE_SECURE_SETTING
            if ("Permission denial: writing to settings requires:android.permission.WRITE_SECURE_SETTINGS".equals(e.getMessage())) {
                Log.e("xxxxxxxxxxxxx", "\n请确保已给予 WRITE_SECURE_SETTINGS 权限\n\n授权代码已复制，请使用adb工具连接手机执行(重启不失效)\n\n");
                ToastUtils.showLong("请给与adb权限: " + e.getMessage());
            }
        }
        return false;
    }

}
